package com.woniuxy.config;

import com.woniuxy.util.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
public class AuthGlobalFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否需要拦截
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("放行预检请求");
            return true;
        }
        String uri = request.getRequestURI();
        System.out.println(uri);
        String token = request.getHeader("token");
        System.out.println(token);
        boolean b = JwtUtils.verifyToken(token);
        if (!b){
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        }
        System.out.println("验签成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


    // 标识当前过滤器的优先级，返回的数字越小，优先级越高
//    @Override
//    public int getOrder() {
//        return 1;
//    }
}